import { defineStore } from 'pinia';
import { v4 as uuidv4 } from 'uuid';

export const useLayerStore = defineStore('layers', {
  state: () => ({
    layers: [],
    selectedLayerId: null,
  }),
  
  getters: {
    selectedLayer: (state) => {
      return state.layers.find(layer => layer.id === state.selectedLayerId);
    },
    
    layerById: (state) => (id) => {
      return findLayerById(state.layers, id);
    },
    
    visibleLayers: (state) => {
      return state.layers.filter(layer => layer.visible);
    }
  },
  
  actions: {
    // 添加新图层
    addLayer(layer) {
      const newLayer = {
        id: uuidv4(),
        name: layer.name || `图层 ${this.layers.length + 1}`,
        type: layer.type || 'object',
        visible: true,
        locked: false,
        opacity: 1,
        fabricObject: layer.fabricObject || null,
        ...layer
      };
      
      this.layers.unshift(newLayer);
      return newLayer.id;
    },
    
    // 更新图层
    updateLayer(id, properties) {
      const layer = findLayerById(this.layers, id);
      if (layer) {
        Object.assign(layer, properties);
      }
    },
    
    // 删除图层
    deleteLayer(id) {
      removeLayerById(this.layers, id);
      if (this.selectedLayerId === id) {
        this.selectedLayerId = this.layers.length > 0 ? this.layers[0].id : null;
      }
    },
    
    // 选择图层
    selectLayer(id) {
      this.selectedLayerId = id;
    },
    
    // 切换图层可见性
    toggleLayerVisibility(id) {
      const layer = findLayerById(this.layers, id);
      if (layer) {
        layer.visible = !layer.visible;
      }
    },
    
    // 切换图层锁定状态
    toggleLayerLock(id) {
      const layer = findLayerById(this.layers, id);
      if (layer) {
        layer.locked = !layer.locked;
      }
    },
    
    // 创建图层组
    createLayerGroup() {
      if (!this.selectedLayerId || this.layers.filter(l => l.selected).length < 2) {
        // 如果没有选中图层或选中少于2个图层，则创建空组
        this.addLayer({
          name: `组 ${this.layers.length + 1}`,
          type: 'group',
          children: []
        });
        return;
      }
      
      // 创建包含所选图层的组
      const selectedLayers = this.layers.filter(l => l.selected);
      const groupId = this.addLayer({
        name: `组 ${this.layers.length + 1}`,
        type: 'group',
        children: selectedLayers
      });
      
      // 移除已添加到组的图层
      selectedLayers.forEach(layer => {
        this.deleteLayer(layer.id);
      });
      
      this.selectLayer(groupId);
    },
    
    // 上移图层
    moveLayerUp(id) {
      const index = this.layers.findIndex(layer => layer.id === id);
      if (index > 0) {
        const temp = this.layers[index];
        this.layers[index] = this.layers[index - 1];
        this.layers[index - 1] = temp;
      }
    },
    
    // 下移图层
    moveLayerDown(id) {
      const index = this.layers.findIndex(layer => layer.id === id);
      if (index < this.layers.length - 1) {
        const temp = this.layers[index];
        this.layers[index] = this.layers[index + 1];
        this.layers[index + 1] = temp;
      }
    },
    
    // 移至顶层
    moveLayerToTop(id) {
      const index = this.layers.findIndex(layer => layer.id === id);
      if (index > 0) {
        const layer = this.layers.splice(index, 1)[0];
        this.layers.unshift(layer);
      }
    },
    
    // 移至底层
    moveLayerToBottom(id) {
      const index = this.layers.findIndex(layer => layer.id === id);
      if (index < this.layers.length - 1) {
        const layer = this.layers.splice(index, 1)[0];
        this.layers.push(layer);
      }
    },
    
    // 重新排序图层
    reorderLayers(newOrder) {
      this.layers = newOrder.map(id => this.layerById(id));
    },
    
    // 清空所有图层
    clearLayers() {
      this.layers = [];
      this.selectedLayerId = null;
    }
  }
});

// 辅助函数：递归查找指定id的图层
function findLayerById(layers, id) {
  for (const layer of layers) {
    if (layer.id === id) {
      return layer;
    }
    
    if (layer.type === 'group' && layer.children?.length > 0) {
      const found = findLayerById(layer.children, id);
      if (found) return found;
    }
  }
  
  return null;
}

// 辅助函数：递归删除指定id的图层
function removeLayerById(layers, id) {
  const index = layers.findIndex(layer => layer.id === id);
  
  if (index !== -1) {
    layers.splice(index, 1);
    return true;
  }
  
  for (const layer of layers) {
    if (layer.type === 'group' && layer.children?.length > 0) {
      if (removeLayerById(layer.children, id)) {
        return true;
      }
    }
  }
  
  return false;
}